package com.ruitaowang.admin.view.api;

import com.ruitaowang.account.security.LYSecurityUtil;
import com.ruitaowang.account.service.SysUserService;
import com.ruitaowang.account.service.WalletService;
import com.ruitaowang.core.domain.*;
import com.ruitaowang.core.properties.ConfigProperties;
import com.ruitaowang.core.utils.StringUtils4RT;
import com.ruitaowang.core.utils.TimeUtils;
import com.ruitaowang.core.utils.aliyun.SendSMSHelper;
import com.ruitaowang.core.web.BaseController;
import com.ruitaowang.core.web.MsgOut;
import com.ruitaowang.goods.service.*;
import org.dom4j.DocumentException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import tech.lingyi.wx.msg.out.TemplateData;
import tech.lingyi.wx.msg.out.TemplateItem;
import wx.wechat.api.API;
import wx.wechat.api.AlonePayAPI;
import wx.wechat.api.PayAPI;
import wx.wechat.common.Configure;
import wx.wechat.service.mp.MPService;
import wx.wechat.utils.XMLUtils;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by neal on 11/17/16.
 */
@Component
@RestController
public class APIWXController extends BaseController {

    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderProdService orderProdService;
    @Autowired
    private LocalOrderService localOrderService;
    @Autowired
    private WXUserinfoService wxUserinfoService;
    @Autowired
    private UserLockService userLockService;
    @Autowired
    private RelationsService relationService;
    @Autowired
    private WalletService walletService;
    @Autowired
    private DistrictService districtService;
    @Autowired
    private CompanyProductService companyProductService;
    @Autowired
    private AddressService addressService;
    @Autowired
    private CompanyService companyService;
    @Autowired
    private UserProfitService userProfitService;
    @Autowired
    private CompanyProfitService companyProfitService;
    @Autowired
    private ConfigProperties configProperties;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private UserMembersService userMembersService;
    @Autowired
    private WalletCompanyService walletCompanyService;
    @Autowired
    private LsMsgService msgService;
//    @Autowired
//    private SimpMessagingTemplate messagingTemplate;
    @Autowired
    private RebateRatioService rebateRatioService;
    @Autowired
    private QRCodeRecordService qrCodeRecordService;
    @Autowired
    private CompanyIndustryService companyIndustryService;
    @Autowired
    private CompanyTypeService companyTypeService;
    @Autowired
    private UserCouponService userCouponService;
    @Autowired
    private ShoppingOrderService shoppingOrderService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private CommentService commentService;
    @Autowired
    private MzAdsService mzAdsService;
    @Autowired
    private CompanyUserService companyUserService;
    @Autowired
    private AjobService ajobService;
    @Autowired
    private LocalDiscountService localDiscountService;
    @Value("${host.api}")
    private String host;
    private Byte isStart;

    private double broker_profit_1_level = 0.4;
    private double broker_profit_2_level = 0.2;
    private double broker_profit_30_level = 0.33;
    private double broker_profit_no_level = 0.1;
    private double broker_profit_score_level = 2.5;//100 socre = 1 RMB

    //一级
    private double overall_profit_1_level = 0.3;
    //二级
    private double overall_profit_2_level = 0.15;
    //一级 奖励金
    private double overall_reward_1_level = 0.03;
    //二级 奖励金
    private double overall_reward_2_level = 0.015;
    //返给自己的红包
    private double overall_profit_myself_level = 0.1;
    //龙蛙收益
    private double overall_profit_RT_level = 0.405;
    //晒单收益
    private double sunburn_profit_price = 0.45;
    //分享人收益
    private double share_profit_price = 0.6;
    //晒单后上级总收益
    private double share_profit_price_level = 0.4;

    InetAddress addr = InetAddress.getLocalHost();
    private String ip=addr.getHostAddress().toString(); //获取本机ip

    public APIWXController() throws UnknownHostException {
        this.ip = ip;
    }

    private void init() {
        //init
        Configure.hostAPI = configProperties.getHostAPI();
        Configure.hostOSS = configProperties.getHostOSS();
        Configure.hostWap = configProperties.getHostWap();
        Configure.returnUri = configProperties.getReturnUri();
        Configure.wxpay_notify_url = configProperties.getHostAPI() + "/api/wxs/notify";
    }
    
    //普通购买商品返利
    @RequestMapping(value = "/api/wxs/prepay")
    public String prepay(@RequestHeader(value="headId",required = false) String userId,Long orderId) {
        init();
        Order order = new Order();
        order.setOrderId(orderId);
        order = orderService.selectByPK(orderId);
        if (order.getPayStatus() ==1){
            return this.renderJson(MsgOut.error("订单已支付，请勿重复提交"));
        }
        int amount = order.getAmountMoney();
        if (amount <= 0) {
            return this.renderJson(MsgOut.success(order));
        }
        PayAPI payAPI = new PayAPI();
        Map<String, Object> map = null;
        String openid = wxUserinfoService.selectByPK(Long.valueOf(userId)).getOpenid();
        try {
            //龙蛙商城-商品
            map = payAPI.prepay("SHOPPING", order.getOrderSn(), amount, openid, "1l" + orderId,
                    API.getClientIpAddress(this.getRequest()));

        } catch (IOException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        MsgOut o = MsgOut.success(map);
        return this.renderJson(o);
    }
    /**
     * @function 更新系统内的订单状态
     */
    @RequestMapping(value = "/api/wxs/notify", method = RequestMethod.GET)
    public String notify(String attach) {
        try {
                String flag = attach.split("l")[0];
                String orderId = attach.split("l")[1];
                //更新订单状态
                if ("1".equals(flag)) {//shop
                    Order order = orderService.selectByPK(Long.valueOf(orderId));
                    if (ObjectUtils.isEmpty(order)) {
                        return "fail";
                    }
                    if (order.getPayStatus() == 0 || order.getPayStatus() == 11) {
                        order.setPayStatus((byte) 1);
                        order.setOrderStatus((byte)2);
                        //更新支付时间
                        order.setPayTime(System.currentTimeMillis());
                        //更新shoppingOrder 支付状态
                        ShoppingOrder shoppingOrder = new ShoppingOrder();
                        shoppingOrder.setOrderId(order.getOrderId());
                        List<ShoppingOrder> shoppingOrders=shoppingOrderService.select(shoppingOrder);
                        for (ShoppingOrder so:shoppingOrders){
                            so.setPayStatus((byte)1);
                            so.setOrderStatus((byte)2);
                            shoppingOrderService.update(so);
                            OrderProd orderProd = new OrderProd();
                            orderProd.setOrderId(so.getOrderId());
                            List<OrderProd> orderProds=orderProdService.select(orderProd);
                            for (OrderProd op:orderProds){
                                Goods goods=goodsService.selectByPK(op.getGoodsId());
                                goods.setGoodsStock(goods.getGoodsStock() - op.getGoodsNumber());
                                goodsService.update(goods);
                            }
                        }
                        orderService.update(order);
                        walletService.createUserProfitForScore(order.getUserId(), order.getAmountScore());
                        setUserProfitNew(order.getOrderSn(), order.getUserId(), order.getOrderAmount(), order.getUserId(), order.getOrderId(), order.getAmountScore(), profit_type_shop_provider_order_money, profit_type_rtshop_myself_money,money_type_score,order.getAmountScore());
                        SysUser sysUser=sysUserService.selectByPK(order.getUserId());
                        if (order.getAmountScore() > 0 ){
                            int scores = 0;
                            Wallet wallet = new Wallet();
                            wallet.setUserId(order.getUserId());
                            List<Wallet> wallets=walletService.select(wallet);
                            if (!ObjectUtils.isEmpty(wallets)){
                                wallet = wallets.get(0);
                                scores = (wallet.getUserScore() + order.getAmountScore())/100;
                            }
                            List<LocalDiscount> localDiscounts = localDiscountService.select(new LocalDiscount());
                            if (!ObjectUtils.isEmpty(localDiscounts)){
                               for (LocalDiscount l:localDiscounts){
                                   if (scores >= l.getScore()){
                                        sysUser.setPosition(l.getTitle());
                                        sysUser.setDepartment(l.getDiscount().toString());
                                        break;
                                   }
                               }
                               sysUserService.update(sysUser);
                            }
                        }
                    }
                }
                return "success";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "fail";
    }

    //    -4 发积分红包
    //    -3 扣除积分
    //    -2 退款
    //    -1  提现
    //    0 供货商订单奖励
    //    1 地面店扫码奖励
    //    2 微商订单奖励
    //    3 地面店扫码返积分
    //    4 微商订单返积分
    //    5 点餐送积分
    //    6 点餐奖励
    //    7 云转奖励
    //    8 云省奖励
    //    9 云签奖励
    //    10 云飞奖励
    //    11 云推奖励
    //    12 云点奖励
    //    13 云联奖励
    //    14 云销奖励
    //    15 云赚奖励
    //    16 互动店商品奖励
    //    17 互动店霸屏奖励
    //    18 互动店打赏奖励
    //    19 互动店抢红包积分
    //    20 互动点区级返利
    //    21 互动点市级返利
    //    22 互动点省级返利

    //购物支付
    private byte profit_type_shop_provider_order_money = 0;
    //扫码支付
    private byte profit_type_dm_sm_order_money = 1;
    //商城购买支付
    private byte profit_type_shop_order_money = 2;

    private byte profit_type_dm_sm_order_score = 3;
    private byte profit_type_shop_ws_order_score = 4;
    private byte profit_type_dc_order_score = 5;
    private byte profit_type_dc_order_money = 6;
    //微传媒1年
    private byte profit_type_mz_order_money = 7;
    //微传媒1个月
    private byte profit_type_mz1_order_money = 23;
    //微传媒3个月
    private byte profit_type_mz3_order_money = 24;
    //微传媒6个月
    private byte profit_type_mz6_order_money = 25;
    //个人二维码推广
    private byte profit_type_qr_order_money = 26;
    //个人店铺押金
    private byte profit_type_pay_300_money = 27;

    //微传媒排行榜奖励红包 2019.2.21
    private byte profit_type_pay_ranking_money = 28;

    //微传媒排行榜奖励红包(间推) 2019.3.25
    private byte profit_type_pay_ranking_money_two = 29;

    private byte profit_type_ks_order_money = 8;
    private byte profit_type_kq_order_money = 9;
    private byte profit_type_kf_order_money = 10;
    private byte profit_type_kt_order_money = 11;
    private byte profit_type_kd_order_money = 12;
    private byte profit_type_kl_order_money = 13;
    private byte profit_type_kx_order_money = 14;
    private byte profit_type_kzz_order_money = 15;
    private byte profit_type_shop_hd_order_money = 16;
    //private byte profit_type_shop_hdp_order_money = 23;
    //    17 互动店霸屏奖励
    private byte profit_type_shop_hd_bashang_money = 17;
    //    18 互动店打赏奖励
    private byte profit_type_shop_hd_dashang_money = 18;
    //    19 互动店抢红包积分
    private byte profit_type_shop_hd_luckmoney_score = 19;
    private byte profit_type_shop_hd_areaLevel_money = 20;
    private byte profit_type_shop_hd_citylevel_money = 21;
    private byte profit_type_shop_hd_provincelevel_money = 22;

    //   1  一级返利
    //   2  二级返利
    //   3  一级返利的返红包奖励金
    //   4  二级返利的返红包奖励金
    //   0  用户本身返现
    private byte profit_type_rtshop_level1_money = 1;
    private byte profit_type_rtshop_level2_money = 2;
    private byte profit_type_rtshop_reward1_money = 3;
    private byte profit_type_rtshop_reward2_money = 4;
    private byte profit_type_rtshop_myself_money = 5;
    private byte profit_type_rtshop_wcmReward_money = 6;

    //   1  现金
    //   2  红包
    private byte money_type_money = 1;
    private byte money_type_score = 2;

    private void setUserProfitNew(String orderSn, Long userId, Integer amount, Long consumerId, Long orderId, Integer profit, int orderType, byte profitType,byte moneyType,int userBalance) {
        LOGGER.info(amount.toString());
        UserProfit userProfit = new UserProfit();
        userProfit.setOrderSn(orderSn);
        userProfit.setUserId(userId);
        userProfit.setAmount(amount);
        userProfit.setConsumerId(consumerId);
        userProfit.setOrderId(orderId);
        userProfit.setUserProfit(profit);
        userProfit.setOrderType((byte) orderType);
        userProfit.setUserBalance(userBalance);
        userProfit.setProfitType(profitType);
        userProfit.setMoneyType(moneyType);
        userProfitService.insert(userProfit);
    }

    private void setCompanyProfit(String orderSn, Long company, Integer amount, Long consumerId, Long orderId, Integer profit, int orderType,int companyBalance) {

        CompanyProfit userProfit = new CompanyProfit();
        userProfit.setOrderSn(orderSn);
        userProfit.setCompanyId(company);
        userProfit.setAmount(amount);
        userProfit.setConsumerId(consumerId);
        userProfit.setOrderId(orderId);
        userProfit.setCompanyProfit(profit);
        userProfit.setOrderType((byte) orderType);
        userProfit.setCompanyBalance(companyBalance);
        companyProfitService.insert(userProfit);
    }

    private void lockUserFromSM(Long orderId) {//user_lock -> offline(local shop) -> online(shoping)
        LocalOrder localOrder = localOrderService.selectByPK(orderId);
        if (ObjectUtils.isEmpty(localOrder)) {
            return;
        }

        Company address = companyService.selectByPK(localOrder.getCompanyId());
        if (ObjectUtils.isEmpty(address) || address.getDistrictId() == 0) {
            return;
        }

        UserLock userLock = userLockService.selectByPK(localOrder.getUserId());
        if (!ObjectUtils.isEmpty(userLock)) {
            return;
        }

        userLock = new UserLock();
        userLock.setUserId(localOrder.getUserId());
        userLock.setProvince(address.getProvince());
        userLock.setCity(address.getCity());
        userLock.setDistrict(address.getDistrict());
        userLock.setDistrictId(address.getDistrictId());
        userLockService.insert(userLock);
    }

    private void lockUserFromShop(Long orderId) {//user_lock -> offline(local shop) -> online(shoping)

        Order order = orderService.selectByPK(orderId);
        if (ObjectUtils.isEmpty(order)) {
            return;
        }
        UserLock userLock = userLockService.selectByPK(order.getUserId());

        Address param = new Address();
        param.setUserId(order.getUserId());
        param.setDefaultt((byte) 1);
        List<Address> addresses = addressService.select(param);
        if (ObjectUtils.isEmpty(addresses) || addresses.size() == 0) {
            return;
        }
        Address address = addresses.get(0);
        if (ObjectUtils.isEmpty(userLock)) {
            userLock = new UserLock();
            userLock.setUserId(order.getUserId());
            userLock.setProvince(address.getProvince());
            userLock.setCity(address.getCity());
            userLock.setDistrict(address.getDistrict());
            userLock.setDistrictId(address.getDistrictId());
            userLockService.insert(userLock);
        } else {
            if (userLock.getDistrictId() != addresses.get(0).getDistrictId()) {
                userLock.setDistrictId(addresses.get(0).getDistrictId());
                userLock.setUserId(order.getUserId());
                userLock.setProvince(address.getProvince());
                userLock.setCity(address.getCity());
                userLock.setDistrict(address.getDistrict());
                userLock.setDistrictId(address.getDistrictId());
                userLockService.update(userLock);
            }
        }

    }

    /**
     * 每天早上9点发送红包到账通知
     */
    @Scheduled(cron = "0 0 9 * * ?")
    //@Scheduled(cron = "0 0 23 * * ?")
    public void sendRankingForNine(){
        LOGGER.info("ip地址为" + ip);
        Ajob ajob = new Ajob();
        //测试环境
        ajob.setAjobSign("testrank900");
        List<Ajob> ajobListcs = getAjob(ajob);
        if (!ObjectUtils.isEmpty(ajobListcs) && ip.equals("10.171.55.220")) {
            isStart = ajobListcs.get(0).getAjobType();
            LOGGER.info("isStart为" + isStart);
            if (isStart == 1){
                ranking(1);
                ranking(2);
            }
        }

        //bmw线上服务器
        ajob.setAjobSign("bmwrank900");
        List<Ajob> ajobListbmw = getAjob(ajob);
        if (!ObjectUtils.isEmpty(ajobListbmw) && ip.equals("10.29.24.137")) {
            isStart = ajobListbmw.get(0).getAjobType();
            if (isStart == 1){
                ranking(1);
                ranking(2);
            }
        }

        //admin线上服务器
        ajob.setAjobSign("adminrank900");
        List<Ajob> ajobListadmin = getAjob(ajob);
        if (!ObjectUtils.isEmpty(ajobListadmin) && ip.equals("10.27.143.116")) {
            isStart = ajobListadmin.get(0).getAjobType();
            if (isStart == 1){
                ranking(1);
                ranking(2);
            }
        }
    }

    public List<Ajob> getAjob(Ajob ajob){
        return ajobService.select(ajob);
    }

    /**
     * 微传媒榜单得奖品发放  第一名50元红包 第二名 30元红包 第三名 20元红包
     */
    private void ranking(int type){

        // 1 2 3 名奖金
        int level1 = 5000 ,level2 = 3000 ,level3 = 2000;

        //获取前一天得开始时间 与 结束时间  获取当天得前三名
        Long stime ,etime;
        stime = TimeUtils.getLongDayBegin() - (24L * 60L * 60L *1000L);
        etime = TimeUtils.getLongDayBegin();
        RelationsVO relationsVO = new RelationsVO();
        relationsVO.setStime(stime);
        relationsVO.setEtime(etime);
        List<RelationsVO> relationsVOS = new ArrayList<>();
        if(type == 1){
            relationsVOS=mzAdsService.selectRanking(relationsVO);
        } else if(type == 2){
            relationsVOS=mzAdsService.selectRankingTwo(relationsVO);
        }
        System.out.println(renderJson(relationsVOS));
        for (int i=0;i < relationsVOS.size();i++){
            System.out.println(i);
            Long userId= relationsVOS.get(i).getId();
            int balance;
            //查询是否已经发放过奖励
            UserProfit userProfit = new UserProfit();
            userProfit.setStime(etime);
            userProfit.setEtime(etime + (24L * 60L * 60L *1000L));
            userProfit.setUserId(relationsVOS.get(i).getId());
            List<UserProfit> userProfits = new ArrayList<>();
            if(type == 1){
                userProfits = userProfitService.selectRankingRewardStatus(userProfit);
            } else if(type == 2){
                userProfits = userProfitService.selectRankingRewardStatusTow(userProfit);
            }
            if (!ObjectUtils.isEmpty(userProfits)){
                //如果数据不为空 跳过此循环
                continue;
            }else {
                if (i==0){//第一名

                    //增加钱包余额
                    walletService.createUserProfitForScore(userId, level1);

                    //增加账户流水
                    balance=walletService.getUserMoney(userId,2);
                    if(type == 1){
                        setUserProfitNew("",userId, level1, 0L, 0L, 5000, profit_type_pay_ranking_money, profit_type_rtshop_wcmReward_money,money_type_score,balance);
                        sendRanking(userId,1,1);
                    } else if(type == 2){
                        setUserProfitNew("",userId, level1, 0L, 0L, 5000, profit_type_pay_ranking_money_two, profit_type_rtshop_wcmReward_money,money_type_score,balance);
                        sendRanking(userId,1,2);
                    }
                }else if (i==1){//第二名

                    //增加钱包余额
                    walletService.createUserProfitForScore(userId, level2);

                    //增加账户流水
                    balance=walletService.getUserMoney(userId,2);
                    if(type == 1){
                        setUserProfitNew("",userId, level2, 0L, 0L, 3000, profit_type_pay_ranking_money, profit_type_rtshop_wcmReward_money,money_type_score,balance);
                        sendRanking(userId,2,1);
                    } else if(type == 2){
                        setUserProfitNew("",userId, level2, 0L, 0L, 3000, profit_type_pay_ranking_money_two, profit_type_rtshop_wcmReward_money,money_type_score,balance);
                        sendRanking(userId,2,2);
                    }
                }else if (i==2){//第三名

                    //增加钱包余额
                    walletService.createUserProfitForScore(userId, level3);

                    //增加账户流水
                    balance=walletService.getUserMoney(userId,2);
                    if(type == 1){
                        setUserProfitNew("",userId, level3, 0L, 0L,2000,profit_type_pay_ranking_money, profit_type_rtshop_wcmReward_money,money_type_score,balance);
                        sendRanking(userId,3,1);
                    } else if(type == 2){
                        setUserProfitNew("",userId, level3, 0L, 0L,2000,profit_type_pay_ranking_money_two, profit_type_rtshop_wcmReward_money,money_type_score,balance);
                        sendRanking(userId,3,2);
                    }
                }
            }

        }
    }

    /**
     * 发送排行榜消息通知
     * @param userId
     * @param type
     */
    public void sendRanking(Long userId,int type,int level) {
        TemplateData templateData = TemplateData.New();
        SNSWXUserinfo snswxUserinfo = wxUserinfoService.selectByPK(userId);
        if (ObjectUtils.isEmpty(snswxUserinfo)) {
            return;
        }
        templateData.setTouser(snswxUserinfo.getOpenid());
        templateData.setTemplate_id("Z6BfT5BWuAWvhF8sED7fs9r5EfvHWgBIdTI0_Kms3VE");
        templateData.setTopcolor("FF0000");
        templateData.setData(new TemplateItem());
        if(level == 1 && type == 1){//直推第一名
            templateData.add("first", "恭喜您，昨日荣登微传媒直推排行榜，奖励您的购物红包已到账，您可在个人中心的购物红包中查看 \n" +
                    "奖励金额50元", "#173177");
            templateData.add("keyword1", "红包金额50元", "#0044BB");
        } else if(level == 1 && type == 2){//直推第二名
            templateData.add("first", "恭喜您，昨日荣登微传媒直推排行榜，奖励您的购物红包已到账，您可在个人中心的购物红包中查看 \n" +
                    "奖励金额30元", "#173177");
            templateData.add("keyword1", "红包金额30元", "#0044BB");
        } else if(level == 1 && type == 3){//直推第三名
            templateData.add("first", "恭喜您，昨日荣登微传媒直推排行榜，奖励您的购物红包已到账，您可在个人中心的购物红包中查看 \n" +
                    "奖励金额20元", "#173177");
            templateData.add("keyword1", "红包金额20元", "#0044BB");
        } else if(level == 2 && type == 1){//间推第一名
            templateData.add("first", "恭喜您，昨日荣登微传媒间推排行榜，奖励您的购物红包已到账，您可在个人中心的购物红包中查看 \n" +
                    "奖励金额50元", "#173177");
            templateData.add("keyword1", "红包金额50元", "#0044BB");
        } else if(level == 2 && type == 2){//间推第二名
            templateData.add("first", "恭喜您，昨日荣登微传媒间推排行榜，奖励您的购物红包已到账，您可在个人中心的购物红包中查看 \n" +
                    "奖励金额30元", "#173177");
            templateData.add("keyword1", "红包金额30元", "#0044BB");
        } else if(level == 2 && type == 3){//间推第三名
            templateData.add("first", "恭喜您，昨日荣登微传媒间推排行榜，奖励您的购物红包已到账，您可在个人中心的购物红包中查看 \n" +
                    "奖励金额20元", "#173177");
            templateData.add("keyword1", "红包金额20元", "#0044BB");
        }
//        if(type == 1){
//            templateData.add("first", "恭喜您，昨日荣登微传媒直推排行榜，奖励您的购物红包已到账，您可在个人中心的购物红包中查看 \n" +
//                    "奖励金额50元", "#173177");
//            templateData.add("keyword1", "红包金额50元", "#0044BB");
//        } else if(type == 2){
//            templateData.add("first", "恭喜您，昨日荣登微传媒直推排行榜，奖励您的购物红包已到账，您可在个人中心的购物红包中查看 \n" +
//                    "奖励金额30元", "#173177");
//            templateData.add("keyword1", "红包金额30元", "#0044BB");
//        } else if(type == 3){
//            templateData.add("first", "恭喜您，昨日荣登微传媒直推排行榜，奖励您的购物红包已到账，您可在个人中心的购物红包中查看 \n" +
//                    "奖励金额20元", "#173177");
//            templateData.add("keyword1", "红包金额20元", "#0044BB");
//        }
        templateData.setUrl(host + "/wap/gxt/cash_earnings");
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        String date =  df.format(new Date());
        templateData.add("keyword2", date, "#0044BB");
        templateData.add("remark", "您可点击详情，进入您的收益明细查看返现详情", "#FF3333");
        try {
            LOGGER.info("templateData {}", templateData);
            new MPService().sendAPIEnter4TemplateMsg(templateData);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     *  发送全员消息（直推）
     */
    @RequestMapping(value = "/sendAllRanking")
    public void sendAllRanking(int type) {
        Long oneUserId = 0L;
        Long twoUserId = 0L;
        Long threeUserId = 0L;
        Long stime ,etime;
        stime = TimeUtils.getLongDayBegin() - (24L * 60L * 60L *1000L);
        etime = TimeUtils.getLongDayBegin();
        RelationsVO relationsVO = new RelationsVO();
        relationsVO.setStime(stime);
        relationsVO.setEtime(etime);
        List<RelationsVO> relationsVOS = new ArrayList<>();
        if(type == 1){
            relationsVOS=mzAdsService.selectRanking(relationsVO);
        } else if(type == 2) {
            relationsVOS=mzAdsService.selectRankingTwo(relationsVO);
        }
        for (int i = 0;i < relationsVOS.size();i++){
            if(i == 0){
                oneUserId= relationsVOS.get(0).getId();
            } else if(i == 1){
                twoUserId= relationsVOS.get(1).getId();
            } else if(i == 2){
                threeUserId= relationsVOS.get(2).getId();
            }
        }
        String oneNmae = "暂无冠军";
        String twoName = "暂无亚军";
        String threeNmae = "暂无季军";
        if (oneUserId != 0){
            oneNmae = sysUserService.selectByPK(oneUserId).getNickname();
        }
        if (twoUserId != 0){
            twoName = sysUserService.selectByPK(twoUserId).getNickname();
        }
        if (threeUserId != 0){
            threeNmae = sysUserService.selectByPK(threeUserId).getNickname();
        }
        SysUser sysUser = new SysUser();
        sysUser.setSubscribe((byte)1);
        List<SysUser> sysUserList = sysUserService.select(sysUser);
        for(int i = 0;i < sysUserList.size();i++){
            TemplateData templateData = TemplateData.New();
            SNSWXUserinfo snswxUserinfo = wxUserinfoService.selectByPK(sysUserList.get(i).getId());
            if (ObjectUtils.isEmpty(snswxUserinfo)) {
                return;
            }
            templateData.setTouser(snswxUserinfo.getOpenid());
            templateData.setTemplate_id("Z6BfT5BWuAWvhF8sED7fs9r5EfvHWgBIdTI0_Kms3VE");
            templateData.setTopcolor("FF0000");
            templateData.setData(new TemplateItem());
            templateData.add("first", "今日排行榜\n" +
                    "冠军：  "+ oneNmae +"，\n奖励购物红包50元\n" +
                    "亚军：  "+ twoName +"，\n奖励购物红包30元\n" +
                    "季军：  "+ threeNmae +"，\n奖励购物红包20元\n" +
                    "以上奖励可在我的-购物红包中查收\r" +
                    "每天使用微传媒广告引流系统，为自己产品引流同时也为首象共享流量，获得荣誉及奖励\r" +
                    "会员们再接再励，明日榜单就是您", "#173177");
            templateData.setUrl(host + "/wap/gxt");
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
            String date =  df.format(new Date());
            templateData.add("keyword1", "按排名进行发放红包", "#0044BB");
            templateData.add("keyword2", date, "#0044BB");
            templateData.add("remark", "感谢你的使用！", "#FF3333");
            try {
                LOGGER.info("templateData {}", templateData);
                new MPService().sendAPIEnter4TemplateMsg(templateData);
                Thread.sleep(5000);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    //商品折扣
    private int getProfitByDiscount(int discount, int who) {

        if (who == 0) {//10级返利
            if (discount >= 80 && discount <= 90) {
                return 100;
            } else if (discount >= 70 && discount < 80) {
                return 200;
            } else if (discount >= 50 && discount < 70) {
                return 300;
            } else if (discount < 50) {
                return 400;
            }
        }

        if (who == 1) {//合伙人返利
            if (discount >= 80 && discount <= 90) {
                return 10;
            } else if (discount >= 70 && discount < 80) {
                return 20;
            } else if (discount >= 50 && discount < 70) {
                return 30;
            } else if (discount < 50) {
                return 40;
            }
        }
        return 0;
    }

    //地面店返利
    private float getProfitBySMDiscountV2(int who) {
//        "邀请人（2.5%） 2       3                    3
//        会员（期限，线上、
//        线下累积消费>¥100）"	城市合伙人（1.25%）	"梦想合伙人（1.25%）
//        邀约关系最近的一个"
//
        if (who == 2) {//地面店 直接邀约人返利
            return 2.50f;
        }

        if (who == 3) {//地面店 合伙人返利
            return 1.25f;
        }

        return 0f;
    }
//    private boolean relationsTime(Long userId,Long qrTime) {
//        Relations relations = new Relations();
//        relations.setUesrId(userId);
//        List<Relations> relationsList=relationService.select(relations);
//        if (ObjectUtils.isEmpty(relationsList)) {
//            return false;
//        }
//        if (relationsList.get(0).getCtime() > qrTime){
//            return true;
//        }else {
//            return false;
//        }
//    }

//    public CompanyProduct giveBackScoreForMicroUserv3(Order goodsOrder) {
//
//        OrderProd whereOrderProd = new OrderProd();
//        whereOrderProd.setGoodsProviderType((byte) 1);
//        whereOrderProd.setOrderId(goodsOrder.getOrderId());
//        List<OrderProd> orderProds = orderProdService.select(whereOrderProd);
//        if (ObjectUtils.isEmpty(orderProds)) {
//            return null;
//        }
//
//        //找出所有的微商
//        Set<Long> microBizUserIds = new HashSet<>();
//
//        for (int i = 0; i < orderProds.size(); i++) {
//            Long microId = null;
//            microId = orderProds.get(i).getGoodsProviderId();
//            if (microId > 0) {
//                microBizUserIds.add(microId);
//            }
//        }
//
//        if (ObjectUtils.isEmpty(microBizUserIds)) {
//            return null;
//        }
//
////计算每个微商返积分 返利
//        List<List<OrderProd>> groupProds = new ArrayList<>(microBizUserIds.size());
//        microBizUserIds.forEach(item -> {
//            List<OrderProd> list = new ArrayList<>();
//            for (int i = 0; i < orderProds.size(); i++) {
//                Long microId = orderProds.get(i).getGoodsProviderId();
//                if (item.longValue() == microId.longValue()) {
//                    list.add(orderProds.get(i));
//                }
//            }
//            groupProds.add(list);
//        });
//
//        if (ObjectUtils.isEmpty(groupProds)) {
//            return null;
//        }
////返积分 返利
//        groupProds.forEach(items -> {
//            int amountMoney = 0;
//            int amountExPrice = 0;
//            Long goodsProviderId = 0L;
//            Long userId = goodsOrder.getUserId();
//            Long prodId = 0L;
//            for (int i = 0; i < items.size(); i++) {
//                prodId = items.get(i).getProdId();
//                amountMoney += items.get(i).getGoodsScreenPrice() * items.get(i).getGoodsNumber();
//                amountExPrice += items.get(i).getXpPrice();
//                goodsProviderId = items.get(i).getGoodsProviderId();
//            }
//            CompanyProduct companyProduct = companyProductService.selectFistDiscount(goodsProviderId);
//            if (ObjectUtils.isEmpty(companyProduct)) {
//                return;
//            }
//            //1 给消费者返积分
//            Byte discountType = companyProduct.getDiscountType();
//            LOGGER.info("discountType  -> {}, ObjectUtils.isEmpty(discountType) -> {}", discountType, ObjectUtils.isEmpty(discountType));
//            if (ObjectUtils.isEmpty(discountType)) {
//                return;
//            }
//            int score = 0;
//            StringBuffer remark = new StringBuffer();
//            if (discountType.intValue() == 0) {
//                int reach5 = companyProduct.getReach5() * 100;
//                int reach4 = companyProduct.getReach4() * 100;
//                int reach3 = companyProduct.getReach3() * 100;
//                int reach2 = companyProduct.getReach2() * 100;
//                int reach1 = companyProduct.getReach1() * 100;
//
//                if (reach5 > 0 && amountMoney >= reach5) {
//                    score = companyProduct.getScore5();
//                } else if (reach4 > 0 && amountMoney >= reach4) {
//                    score = companyProduct.getScore4();
//                } else if (reach3 > 0 && amountMoney >= reach3) {
//                    score = companyProduct.getScore3();
//                } else if (reach2 > 0 && amountMoney >= reach2) {
//                    score = companyProduct.getScore2();
//                } else if (reach1 > 0 && amountMoney >= reach1) {
//                    score = companyProduct.getScore1();
//                }
//                remark.append("reach1=").append(reach1).append(", score1=").append(companyProduct.getScore1()).append("|");
//                remark.append("reach2=").append(reach2).append(", score2=").append(companyProduct.getScore2()).append("|");
//                remark.append("reach3=").append(reach3).append(", score3=").append(companyProduct.getScore3()).append("|");
//                remark.append("reach4=").append(reach4).append(", score4=").append(companyProduct.getScore4()).append("|");
//                remark.append("reach5=").append(reach5).append(", score5=").append(companyProduct.getScore5()).append("|");
//            }
//            if (discountType.intValue() == 1) {
//                score = companyProduct.getPercentage() * amountMoney / 100;
//                remark.append(companyProduct.getPercentage()).append("%");
//            }
//            LOGGER.info("消费者得到的积分: score={}, 龙蛙获得的利润: money={}, 订单总额：price={}, discountType={}, fan={}", score, score / 2, amountMoney, discountType, remark);
//
//            //socre = 0 不需要记录
//
//            if (score <= 0) {
//                return;
//            }
//
//            //更新每个的积分 discount
//            OrderProd op = new OrderProd();
//            op.setGiveScore(score);
//            op.setRemark(remark.toString());
//            op.setProdId(prodId);
//            orderProdService.update(op);
//
//            //消费者得积分
//            LOGGER.info("---------- 消费者得积分 ----------");
//            Wallet wallet = walletService.selectByPK(userId);
//            LOGGER.info("localOrder.getUserId() ---------- {}", userId);
//            if (ObjectUtils.isEmpty(wallet)) {
//                wallet = new Wallet();
//                wallet.setUserId(userId);
//                wallet.setUserScore(score);
//                wallet.setUserScoreTotal(score);
//                walletService.insert(wallet);
//            } else {
//                wallet.setUserScore(wallet.getUserScore() + score);
//                wallet.setUserScoreTotal(wallet.getUserScoreTotal() + score);
//                walletService.update(wallet);
//            }
//            setUserProfit(goodsOrder.getOrderSn(), wallet.getUserId(), amountMoney, wallet.getUserId(), goodsOrder.getOrderId(), score, this.profit_type_shop_ws_order_score);
//
//            Company company = companyService.selectByPK(companyProduct.getCompanyId());
//            if (ObjectUtils.isEmpty(company)) {
//                return;
//            }
//
//            userId = company.getUserId();//微商的邀约人
//
//            //地面店收钱
//            LOGGER.info("---------- 微商收钱 ----------");//订单显示收入流水 公司钱包
//            WalletCompany walletCompany = walletCompanyService.selectByPK(companyProduct.getCompanyId());
//            Integer add = amountMoney + amountExPrice - score;
//
//            if (ObjectUtils.isEmpty(walletCompany)) {
//                walletCompany = new WalletCompany();
//                walletCompany.setCompanyId(companyProduct.getCompanyId());
//                walletCompany.setCompanyAmount(add);
//                walletCompany.setCompanyBalance(walletCompany.getCompanyAmount());
//                walletCompanyService.insert(walletCompany);
//            } else {
//                walletCompany.setCompanyAmount(walletCompany.getCompanyAmount() + add);
//                walletCompany.setCompanyBalance(walletCompany.getCompanyBalance() + add);
//                walletCompanyService.update(walletCompany);
//            }
//
//            //微商
//            //分润
//            //二级 40 20 10 30
//
//            List<Long> parents = relationService.selectAllParents(userId);
//            int profitForTotal = (int) (score * broker_profit_score_level / 100);
//            if (!ObjectUtils.isEmpty(parents) && parents.size() > 1) {
//                Collections.reverse(parents);
//                int len = parents.size();
//                len = len >= 3 ? 3 : len;//只取两级
//
//                for (int i = 1; i < len; i++) {
//                    //区代理
//                    if (i == 1) {//包括区代和个贷 40%
//                        int level1 = (int) (profitForTotal * broker_profit_1_level);
//                        if (!ObjectUtils.isEmpty(userMembersService.selectMemberForKTByUserId(parents.get(i)))) {
//                            walletService.createUserProfit(parents.get(i), level1);
//                            setUserProfit(goodsOrder.getOrderSn(), parents.get(i), goodsOrder.getAmountMoney(), goodsOrder.getUserId(), goodsOrder.getOrderId(), level1, profit_type_shop_ws_order_money);
//
//                        } else if (!ObjectUtils.isEmpty(userMembersService.selectMemberForKFByUserId(parents.get(i)))) {
//                            walletService.createUserProfit(parents.get(i), level1);
//                            setUserProfit(goodsOrder.getOrderSn(), parents.get(i), goodsOrder.getAmountMoney(), goodsOrder.getUserId(), goodsOrder.getOrderId(), level1, profit_type_shop_ws_order_money);
//
//                        }
//                    }
//                    if (i == 2) {//包括区代和个贷 20%
//                        int level2 = (int) (profitForTotal * broker_profit_2_level);
//                        if (!ObjectUtils.isEmpty(userMembersService.selectMemberForKTByUserId(parents.get(i)))) {
//                            walletService.createUserProfit(parents.get(i), level2);
//                            setUserProfit(goodsOrder.getOrderSn(), parents.get(i), goodsOrder.getAmountMoney(), goodsOrder.getUserId(), goodsOrder.getOrderId(), level2, profit_type_shop_ws_order_money);
//
//                        } else if (!ObjectUtils.isEmpty(userMembersService.selectMemberForKFByUserId(parents.get(i)))) {
//                            walletService.createUserProfit(parents.get(i), level2);
//                            setUserProfit(goodsOrder.getOrderSn(), parents.get(i), goodsOrder.getAmountMoney(), goodsOrder.getUserId(), goodsOrder.getOrderId(), level2, profit_type_shop_ws_order_money);
//                        }
//                    }
//                }
//            }
//
//            //区代 管理费 10%
//            UserLock userLock = userLockService.selectByPK(goodsOrder.getUserId());
//            if (!ObjectUtils.isEmpty(userLock)) {
//                Long districtId = userLock.getDistrictId();
//                District district = districtService.selectByPK(districtId);
//                if (!ObjectUtils.isEmpty(district)) {
//                    Long cityUserId = district.getCityUserId();
//                    int nolevel = (int) (profitForTotal * broker_profit_no_level);
//                    if (!ObjectUtils.isEmpty(cityUserId) && cityUserId > 0 && !ObjectUtils.isEmpty(userMembersService.getMemberForKTLimitV2(cityUserId, districtId))) {
//                        walletService.createUserProfit(cityUserId, nolevel);
//                        //流水
//                        setUserProfit(goodsOrder.getOrderSn(), cityUserId, goodsOrder.getAmountMoney(), goodsOrder.getUserId(), goodsOrder.getOrderId(), nolevel, profit_type_shop_ws_order_money);
//                    }
//                }
//            }
//
//        });
//        return null;
//    }

//    @RequestMapping(value = "/api/wxs/testws")
//    public String test(Long orderId) {
//        LsMsg lsMsg = msgService.selectByPK(orderId);
//        this.messagingTemplate.convertAndSend("/topic/hi/" + lsMsg.getCompanyId(), lsMsg);
//        return this.renderJson(MsgOut.success(lsMsg));
//    }

//    @RequestMapping(value = "/api/wxs/testhd")
//    public String testapp(Long orderId) {
//        LsMsg lsMsg = msgService.selectByPK(orderId);
//        this.messagingTemplate.convertAndSend("/topic/notify/hd/" + lsMsg.getCompanyId(), MsgOut.success(lsMsg));
//        return this.renderJson(MsgOut.success(lsMsg));
//    }

    @RequestMapping(value = "/api/wxs/config")
    public String wxShareConfig(String url) throws Exception {
//        noncestr=Wm3WZYTPz0wzccnW
//        jsapi_ticket=sM4AOVdWfPE4DxkXGEs8VMCPGGVi4C3VM0P37wVUCFvkVAy_90u5h9nbSlYy3-Sl-HhTdfl2fzFy1AOcHKP7qg
//        timestamp=1414587457
//        url=http://mp.weixin.qq.com?params=value

        MPService mpService = new MPService();
        return this.renderJson(MsgOut.success(mpService.wxShareConfig(url)));
    }

    @RequestMapping(value = "/api/wxs/saomapay", method = RequestMethod.POST)
    public String saomapay(@RequestBody byte[] bytes) throws Exception {
        String notify = new String(bytes, "UTF-8");
        LOGGER.info("bytes {}", notify);
        Object attach = XMLUtils.XML2Map(notify);
        LOGGER.info("xml {}", attach);
        MsgOut o = MsgOut.success("");
        return this.renderJson(o);
    }

    /**
     * 购买微传媒或者升级高级合伙人的模板消息通知
     * @param parentId
     * @param userId
     * @param date
     * @param type
     * @param payStatus
     * @param profit
     */
    public void buildQRNotify(Long parentId, Long userId, String date, int type, int payStatus, double profit) {
        TemplateData templateData = TemplateData.New();
        SNSWXUserinfo snswxUserinfo = wxUserinfoService.selectByPK(parentId);
        if (ObjectUtils.isEmpty(snswxUserinfo)) {
            return;
        }
        templateData.setTouser(snswxUserinfo.getOpenid());
        templateData.setTemplate_id("16mfGGaQ54u-ehnM1PUW5q6DTUCj8svOm_OFCc39FXE");
        templateData.setTopcolor("FF0000");
        templateData.setData(new TemplateItem());
        if(payStatus == 1 && type == 1){
            templateData.add("first", "恭喜您，您的直推已成功购买了微传媒一年的使用权限！您获得30%的返现30.00元", "#173177");
        } else if(payStatus == 1 && type == 2){
            templateData.add("first", "恭喜您，您的间推已成功购买了微传媒一年的使用权限！您获得15%的返现15.00元", "#173177");
        }else if(payStatus == 1 && type == 3){
            templateData.add("first", "恭喜您，您的间推通过下级购买微传媒一年的使用权限获得返利！您获得10%的返现"+ profit +"元", "#173177");
        } else if(payStatus == 2 && type == 1){
            templateData.add("first", "恭喜您，您的直推已升级为高级合伙人！您获得30%的返现600.00元", "#173177");
        } else if (payStatus == 2 && type == 2){
            templateData.add("first", "恭喜您，您的间推已升级为高级合伙人！您获得15%的返现300.00元", "#173177");
        } else if (payStatus == 2 && type == 3){
            templateData.add("first", "恭喜您，您的间推通过下级升级为高级合伙人获得返利！您获得10%的返现"+ profit +"元", "#173177");
        } else if (payStatus == 3 && type == 1){
            templateData.add("first", "恭喜您，您的直推已经消费300元开通个人商户！您获得30%的返现90.00元", "#173177");
        } else if (payStatus == 3 && type == 2){
            templateData.add("first", "恭喜您，您的间推已经消费300元开通个人商户！您获得15%的返现45.00元", "#173177");
        } else if (payStatus == 3 && type == 3){
            templateData.add("first", "恭喜您，您的间推通过下级消费300元开通个人商户获得返利！您获得10%的返现"+ profit +"元", "#173177");
        } else if (payStatus == 4 && type == 1){
            templateData.add("first", "恭喜您，您的直推已经消费599元开通社群！您获得30%的返现180.00元", "#173177");
        } else if (payStatus == 4 && type == 2){
            templateData.add("first", "恭喜您，您的间推已经消费599元开通社群！您获得15%的返现900.00元", "#173177");
        } else if (payStatus == 4 && type == 3){
            templateData.add("first", "恭喜您，您的间推通过下级消费599元开通社群获得返利！您获得10%的返现"+ profit +"元", "#173177");
        }
        templateData.setUrl(host + "/wap/gxt/cash_earnings");
        String username = sysUserService.selectByPK(userId).getNickname();
        templateData.add("keyword1", username, "#0044BB");
        if(payStatus == 1){
            templateData.add("keyword2", "微传媒一年的使用权限", "#0044BB");
            templateData.add("keyword3", "99.00元", "#0044BB");
        } else if(payStatus == 2){
            templateData.add("keyword2", "首象共享高级会员", "#0044BB");
            templateData.add("keyword3", "2000.00元", "#0044BB");
        } else if(payStatus == 3){
            templateData.add("keyword2", "个人商户权限", "#0044BB");
            templateData.add("keyword3", "300.00元", "#0044BB");
        } else if(payStatus == 4){
            templateData.add("keyword2", "社群权限", "#0044BB");
            templateData.add("keyword3", "599.00元", "#0044BB");
        }
        templateData.add("keyword4", date, "#0044BB");
        templateData.add("remark", "您可点击详情，进入您的收益明细查看返现详情", "#FF3333");
        try {
            LOGGER.info("templateData {}", templateData);
            new MPService().sendAPIEnter4TemplateMsg(templateData);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void buildQRNotify(Long parentId,Long userId,String date,int type,int payMoney,int fanliMoney) {
        TemplateData templateData = TemplateData.New();
        SNSWXUserinfo snswxUserinfo = wxUserinfoService.selectByPK(parentId);
        if (ObjectUtils.isEmpty(snswxUserinfo)) {
            return;
        }
        templateData.setTouser(snswxUserinfo.getOpenid());
        templateData.setTemplate_id("16mfGGaQ54u-ehnM1PUW5q6DTUCj8svOm_OFCc39FXE");
        templateData.setTopcolor("FF0000");
        templateData.setData(new TemplateItem());
        if(type == 1){
            templateData.add("first", "恭喜您，您的直推已成功消费！平台提供给您的返现是" + fanliMoney * 0.01 + "元", "#173177");
        } else if(type == 2){
            templateData.add("first", "恭喜您，您的间推已成功消费！平台提供给您的返现是" + fanliMoney * 0.01 + "元", "#173177");
        } else if(type == 3){
            templateData.add("first", "恭喜您，您的间推获得收益，平台提供给您的返现是" + fanliMoney * 0.01 + "元", "#173177");
        }
        templateData.setUrl(host + "/wap/gxt/cash_earnings");
        String username = sysUserService.selectByPK(userId).getNickname();
        templateData.add("keyword1", username, "#0044BB");
        templateData.add("keyword2", "平台内商品", "#0044BB");
        templateData.add("keyword3", String.valueOf(payMoney * 0.01), "#0044BB");
        templateData.add("keyword4", date, "#0044BB");
        templateData.add("remark", "您可点击详情，进入您的收益明细查看返现详情", "#FF3333");
        try {
            LOGGER.info("templateData {}", templateData);
            new MPService().sendAPIEnter4TemplateMsg(templateData);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
